
let email = null,
    phone = null,
    copyEmail = email,
    copyPhone = phone,
    emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
    phoneReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

let initAccount = async () => {
    await getUserAccount()
    listenerEmailInput()
    listenerPhoneInput()
    listenerSave()
    listenerUploadImg()
}

// get user info
let getUserAccount = async () => {
    let res = await ajax('student_detailed_query', {}, 'post')
    email = res.data.mailbox
    phone = res.data.phone
    copyEmail = res.data.mailbox
    copyPhone = res.data.phone
    return res.data
}

// email input 
let listenerEmailInput = () => {
    $('.account-input3')[0].addEventListener('change', (e) => {
        email = e.target.value
    })
}


// phone input
let listenerPhoneInput = () => {
    $('.account-input4')[0].addEventListener('change', (e) => {
        phone = e.target.value
    })
}

// save 
let listenerSave = () => {
    $('.account-save-btn')[0].addEventListener('click', async (e) => {
        let isEmailTrue = emailReg.test(email)
        if (isEmailTrue && email !== copyEmail || phone !== copyPhone) {
            let res = await ajax(
                'student_mailbox_phone_update',
                {
                    mailbox: email,
                    phone: phone
                },
                'post'
            )
            if (res.code === 200) {
                Dreamer.success("修改成功", 2000);
            } else {
                Dreamer.success("修改失败", 2000);
            }
        }
        console.log(email, phone)
    })
}

// upload
let listenerUploadImg = () => {
    $('.account-upload')[0].addEventListener('click', () => {
        let input = document.createElement('input')
        input.className = 'input'
        input.type = 'file'
        input.accept = 'image/*'
        input.addEventListener('change', async (e) => {
            if (e.target.files[0]) {
                let {
                    url
                } = await unploadimg(e.target.files[0],1024 * 1024 * 1024)
                if (url) {
                    let upimg = await ajax('teacher_img_update', { 'teacherimg': url }, 'post')
                    Dreamer.success('上传成功')
                    $('.account-image')[0].src = url
                    let user = JSON.parse(localStorage.getItem('user'))
                    user.user_img = url

                    $('.avatar').attr('src', url)
                    // // 上传头像，实现刷新缓存一下头像显示

                    let infor = JSON.parse(localStorage.getItem('information'))

                    infor.teacherimg = url;

                    localStorage.removeItem('information')
                    localStorage.setItem('information', JSON.stringify(infor))

                    localStorage.setItem('user', JSON.stringify(user))
                }


            }

        })
        input.click()
    })
}

// del


export {
    initAccount,
    getUserAccount
} 